<?php
namespace Api\Controller;

use Api\Qywechat\WXBizMsgCrypt;
use Think\Controller;

class WechatController extends Controller
{

    private $encodingAesKey = "ZCSRASnGQIXKowapLhcfAniuyMWRXeyIPlrFsHITxpb";

    private $token = "jyLAQlQNqc9PdSrkPToh";

    private $corpId = "wx78421f21ad5398e1";
    // private $corpId = "wxe657f65dd65ec56e";
    private $secret = "VBtg6sr-RASByoUz4JAo8l-diZ7ptUCSPDnZBxxiNcESuaz3y4ihqktEgYWi2cwM";

    private $access_token = "";
    
    private $apiurl = "http://oa.kingtoinc.com/erp/getRoomByID/";

    public function __construct()
    {
        $this->access_token = $this->get_accessToken();
    }

    public function index()
    {
        // 企业号在公众平台上设置的参数如下
        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];
        $sVerifyNonce = $_GET['nonce'];
        $sVerifyEchoStr = urldecode($_GET['echostr']);
        // 需要返回的明文
        $sEchoStr = "";
        $wxcpt = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->corpId);
        if ($sVerifyEchoStr) {
            $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
            if ($errCode == 0) {
                ob_clean();
                echo $sEchoStr;
                exit();
            } else {
                print("ERR: " . $errCode . "\n\n");
            }
        } else {
            S(array(
                'type' => 'file'
            ));
            
            $sMsg = $this->reply_qy();
            $xml = new \DOMDocument();
            $xml->loadXML($sMsg);
            $logFile = fopen("Log/".date("Y-m-d").".log","a+");
            $ToUserName = $xml->getElementsByTagName('FromUserName')->item(0)->nodeValue;
            // 有BUG，接收用户消息后会连续调用三次微信接口，这里做一个2秒的缓存，2秒内对同一用户的提交只做一次返回处理
            if (!S($ToUserName)) {
                S($ToUserName, "为修复bug而建立的缓存，内容不重要！", 2);
                $MsgType = $xml->getElementsByTagName("MsgType")->item(0)->nodeValue;
                $AgentID = $xml->getElementsByTagName("AgentID")->item(0)->nodeValue;
                if($MsgType=="text"){
                    $Content = $xml->getElementsByTagName('Content')->item(0)->nodeValue;
                    //根据微信接收内容通过接口查询铺位信息
                    $Content = strtoupper($Content);
                    $jsonstr = $this->get_curl($this->apiurl.$Content);
                    $obj = json_decode($jsonstr);
                    fwrite($logFile, "【".date("Y-m-d H:i:s")."】".$ToUserName."　输入查询　".$Content."　".$obj->number."\r\n");
                    if($obj->number){
                        if($obj->state=="待租"){
                            $tmplstr = "铺位号：".$obj->number."\n铺位状态：".$obj->state."\n铺位面积：".$obj->area."㎡\n待租日期：".$obj->emptydate;
                        }else if ($obj->state=="未放租"){
                            $tmplstr = "铺位号：".$obj->number."\n铺位状态：".$obj->state."\n铺位面积：".$obj->area."㎡";
                        }
                        else{
                           $tmplstr = "铺位号：".$obj->number."\n铺位状态：".$obj->state."\n铺位面积：".$obj->area."㎡\n客户名称：".$obj->customer."\n起租日期：".$obj->startdate."\n"
                                ."到期日期：".$obj->enddate."\n对应铺位：".substr($obj->tenroom,19)."\n联系电话：".$obj->phone;
                        }
                    }else{
                        $tmplstr = "未查到该铺位信息！";
                    }
                    $this->send_text($ToUserName, $AgentID, $tmplstr);
                }elseif ($MsgType=="event"){
                    $Event = $xml->getElementsByTagName("Event")->item(0)->nodeValue;
                    $EventKey = $xml->getElementsByTagName("EventKey")->item(0)->nodeValue;
                    if($Event=="scancode_waitmsg"&&$EventKey="key_1"){
                        $ScanResult = $xml->getElementsByTagName("ScanResult")->item(0)->nodeValue;
                        $jsonstr = $this->get_curl($this->apiurl.urlencode($ScanResult));
                        $obj = json_decode($jsonstr);
                        fwrite($logFile, "【".date("Y-m-d H:i:s")."】".$ToUserName."　扫码查询　".$ScanResult."　".$obj->number."\r\n");
                        if($obj->number){
                            if($obj->state=="待租"){
                                $tmplstr = "铺位号：".$obj->number."\n铺位状态：".$obj->state."\n铺位面积：".$obj->area."㎡\n待租日期：".$obj->emptydate;
                            }else{
                                $tmplstr = "铺位号：".$obj->number."\n铺位状态：".$obj->state."\n铺位面积：".$obj->area."㎡\n客户名称：".$obj->customer."\n起租日期：".$obj->startdate."\n"
                                ."到期日期：".$obj->enddate."\n对应铺位：".substr($obj->tenroom,19)."\n联系电话：".$obj->phone;
                            }
                        }else{
                            $tmplstr = "未查到该铺位信息！";
                        }
                        $this->send_text($ToUserName, $AgentID, $tmplstr);
                    }
                }
                fclose($logFile);
                
            }
        }
    }

    /* ------------使用示例二：对用户回复的消息解密--------------- */
    private function reply_qy()
    {
        $wxcpt = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->corpId);
        $sReqMsgSig = $_REQUEST['msg_signature'];
        $sReqTimeStamp = $_REQUEST["timestamp"];
        $sReqNonce = $_REQUEST['nonce'];
        $sReqData = $GLOBALS["HTTP_RAW_POST_DATA"];
        
        $sMsg = ""; // 解析之后的明文
        $errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
        if ($errCode == 0) {
            return $sMsg;
        } else {
            return $errCode;
        }
    }
    
    // ------------使用示例三：企业回复用户消息的加密---------------
 /*    private function qy_text($ToUserName, $FromUserName, $CreateTime, $Content, $MsgId, $AgentID)
    {
        // 需要发送的明文
        $sReqTimeStamp = $_REQUEST["timestamp"];
        $sReqNonce = $_REQUEST['nonce'];
        $sRespData = "<xml><ToUserName><![CDATA[" . $ToUserName . "]]></ToUserName><FromUserName><![CDATA[" . $FromUserName . "]]></FromUserName><CreateTime>" . $CreateTime . "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" . $Content . "1" . "]]></Content><MsgId>" . $MsgId . "</MsgId><AgentID>" . $AgentID . "</AgentID></xml>";
        $sEncryptMsg = ""; // xml格式的密文
        $wxcpt = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->corpId);
        $errCode = $wxcpt->EncryptMsg($sRespData, $sReqTimeStamp, $sReqNonce, $sEncryptMsg);
        if ($errCode == 0) {
            echo json_encode($sEncryptMsg);
            // $res = $this->get_curl("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$this->access_token,$sEncryptMsg);
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
    } */

    /* 发送文本消息接口 */
    private function send_text($touser, $agentid, $content)
    {
        $text_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" . $this->access_token;
        $data = '{
                   "touser": "' . $touser . '",
                   "msgtype": "text",
                   "agentid": ' . $agentid . ',
                   "text": {
                       "content": "' . $content . '"
                   },
                   "safe":0
                }';
        $res = $this->get_curl($text_url, $data);
    }

    private function get_accessToken()
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $this->corpId . "&corpsecret=" . $this->secret;
        S(array(
            'type' => 'file',
            'expire' => 6000
        ));
        $access_token = S("access_token");
        if ($access_token == "") {
            $access_token = $this->get_curl($url);
            S("access_token", $access_token);
        }
        return json_decode($access_token)->access_token;
    }

    private function get_curl($url, $data = '')
    {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if ($data) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        
        $res = curl_exec($ch);
        
        curl_close($ch);
        return $res;
    }
}
?>